package com.linq.cool.common.security.feign;


import com.linq.cool.common.constants.CacheConstants;
import com.linq.cool.common.core.utils.ServletUtils;
import com.linq.cool.common.core.utils.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author: yqlin
 * @Date: 2020/12/29 16:53
 * @Description: feign 请求拦截器
 * @Version: 1.0.0
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request = ServletUtils.getRequest();
        if (StringUtils.isNotNull(request)) {
            Map<String, String> headers = ServletUtils.getHeaders(request);
            String userId = headers.get(CacheConstants.DETAILS_USER_ID);
            if (StringUtils.isNotEmpty(userId)) {
                requestTemplate.header(CacheConstants.DETAILS_USER_ID, userId);
            }
            String username = headers.get(CacheConstants.DETAILS_USERNAME);
            if (StringUtils.isNotEmpty(username)) {
                requestTemplate.header(CacheConstants.DETAILS_USERNAME, username);
            }
            String openId = headers.get(CacheConstants.DETAILS_OPEN_ID);
            if (StringUtils.isNotEmpty(openId)) {
                requestTemplate.header(CacheConstants.DETAILS_OPEN_ID, openId);
            }
            String authentication = headers.get(CacheConstants.AUTHORIZATION_HEADER);
            if (StringUtils.isNotEmpty(authentication)) {
                requestTemplate.header(CacheConstants.AUTHORIZATION_HEADER, authentication);
            }
        }
    }
}
